﻿using LuShanTea.DTO;
using LuShanTea.Front.Web.App_Start;
using LuShanTea.Front.Web.Models;
using LuShanTea.IService;
using LuShanTea.Service;
using LuShanTea.Web.Common;
using PlainElastic.Net.Queries;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;

namespace LuShanTea.Front.Web.Controllers
{
    public class HomeController : Controller
    {
        public IGoodService goodSer { get; set; }
        public ICategoryService categorySer { get; set; }
        public IGoodImsSrcService goodImgSer { get; set; }
        public ICommentService commentSer { get; set; }
        public IGoodAttrService goodAttrSer { get; set; }
        public IPackService packSer { get; set; }
        public IOrderRecordService OrderRecordSer { get; set; }
        public IGoodImsSrcService GoodImgSrcService { get; set; }
        public ICartRecordService CartRecordService { get; set; }
        public ICartService CartService { get; set; }

        [IsLogin]
        [HttpPost]
        public ActionResult Exit()
        {
            Session.Abandon();
            return Json(new AjaxResult {Status="ok" });
        }


        // 首页展示
        public ActionResult Index()
        {
            // 获取商品所有类型
            var categorys = categorySer.GetAll().Take(6).ToArray();

            // 获取巴山雀舌系列商品类型下的前8条商品
            //GoodDTO[] goods = goodSer.GetGoodsByCategId(1).Take(8).ToArray();
            GoodDTO[] goods = goodSer.GetTakeGoodsByCategId(1).ToArray();
            List<GoodImgSrcDTO> listGoodImg = GetGoodsImg(goods);

            // 获取庐山云雾茶系列商品类型下的前8条商品
            GoodDTO[] goodsLuShanTeas = goodSer.GetTakeGoodsByCategId(5).ToArray();
            List<GoodImgSrcDTO> listLuShanTeaGoodImgs = GetGoodsImg(goodsLuShanTeas);

            // 获取庐山云雾茶系列商品类型下的前8条商品
            GoodDTO[] goodsTeaTools = goodSer.GetTakeGoodsByCategId(8).ToArray();
            List<GoodImgSrcDTO> listTeaToolImgs = GetGoodsImg(goodsTeaTools);

            // 获取热销前5件商品
            GoodDTO[] hotSaleGoods = goodSer.GetSelledTakeAll();
            List<GoodImgSrcDTO> hotSaleGoodImgs = GetGoodsImg(hotSaleGoods);
            List<int> hotSaleGoodComments = GetGoodComments(hotSaleGoods);

            // 获取最新上线的5件商品
            GoodDTO[] latestOnlineGoods = goodSer.GetNewTakeAll();
            List<GoodImgSrcDTO> latestOnlineGoodImgs = GetGoodsImg(latestOnlineGoods);
            List<int> latestOnlineGoodComments = GetGoodComments(latestOnlineGoods);

            IndexGoodGetModel model = new IndexGoodGetModel();
            model.Goods = goods;
            model.GoodImgs = listGoodImg;
            model.Categorys = categorys;
            model.GoodsLuShanTeas = goodsLuShanTeas;
            model.ListLuShanTeaGoodImgs = listLuShanTeaGoodImgs;
            model.GoodsTeaTools = goodsTeaTools;
            model.ListTeaToolImgs = listTeaToolImgs;
            model.HotSaleGoods = hotSaleGoods;
            model.HotSaleGoodImgs = hotSaleGoodImgs;
            model.hotSaleGoodComments = hotSaleGoodComments;
            model.LatestOnlineGoods = latestOnlineGoods;
            model.LatestOnlineGoodImgs = latestOnlineGoodImgs;
            model.LatestOnlineGoodComments = latestOnlineGoodComments;

            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            //objCache.Insert("LuShanTea_Front_index_Model", model,null);
            var result= objCache.Get("LuShanTea_Front_index_Model");
            if (result != null)
            {
                IndexGoodGetModel model2 = (IndexGoodGetModel)result;
                return View(model2);
            }
            

            return View(model);
        }


        // 商品详情显示
        public ActionResult Detail(long goodId)
        {


            var good = goodSer.GetByGoodId(goodId); // 根据商品id获取该商品
            if (good == null)
            {
                return HttpNotFound("该商品不存在");
            }
            //var goodImgs = goodImgSer.GetImgsByGoodId(goodId); // 根据商品id获取该商品的所有图片
            //var goodImgs = GetGoodsImg(new GoodDTO[] { good }).ToArray();

            var goodImgs = GetGoodsImgs(new GoodDTO[] { good }).ToArray();

            CommentDTO[] goodComments = commentSer.GetAll().Where(e => e.GoodId == goodId).ToArray(); // 获取指定商品id的所有评论


            GoodAttrDTO goodAttr = goodAttrSer.GetAttrByGoodId(goodId);
            if (goodAttr == null)
            {
                goodAttr = new GoodAttrDTO();
                goodAttr.ArtDesc = "";
                goodAttr.GoodId = good.Id;
                goodAttr.Level = "1";
                goodAttr.ProduceTime = DateTime.Now;
                goodAttr.ProNumber = "";
                goodAttr.ValidTime = "";
            }

            var goodPacks = packSer.GetPackByGoodId(goodId);

            GoodDetailGetModel model = new GoodDetailGetModel();
            model.Good = good;
            model.GoodImgs = goodImgs;
            model.GoodComments = goodComments;
            model.GoodAttr = goodAttr;
            model.GoodPacks = goodPacks;
            return View(model);
        }




        // 商品展示
        [HttpGet]
        public ActionResult List(long categoryId = 1)
        {

            var categorys = categorySer.GetAll().ToArray();// 获取所有商品类型
            var packs = packSer.GetAll().ToArray(); // 获取所有包装类型
            //var goods = goodSer.GetGoodsByCategId(categoryId).ToArray();// 获取指定类型下的所有商品
            // 判断categoryId传过来的值是否为0，如果为0 则表示获取所有类型商品
            var goods = goodSer.GetPageDataGoodsByCategId(categoryId, 1, "all", "0-0", 0, "").ToArray();

            List<GoodImgSrcDTO> goodImgs = GetGoodsImg(goods); // 获取指定商品的图片
            List<int> goodComments = GetGoodComments(goods); // 获取指定商品的评论数
            ViewBag.goodCount = goodSer.GetGoodsByCategId(categoryId).Count(); // 获取所有商品总数

            GoodListGetModel model = new GoodListGetModel();
            model.Categorys = categorys;
            model.Packs = packs;
            model.Goods = goods;
            model.GoodImgs = goodImgs;
            model.GoodComments = goodComments;
            model.CategoryId = categoryId;
            return View(model);
        }

        /// <summary>
        /// 筛选出符合条件的商品
        /// </summary>
        /// <param name="categoryId">商品类型id</param>
        /// <param name="index">获取第几页</param>
        /// <param name="orderBy">排序规则</param>
        /// <param name="priceRange">商品价钱区间</param>
        /// <param name="packId">商品包装id</param>
        /// <param name="keyword">关键字</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult List(long categoryId = 1, int index = 1, string orderBy = "all", string priceRange = "0-0", long packId = 0, string keyword = "")
        {


            var categorys = categorySer.GetAll().ToArray();// 获取所有商品类型
            var packs = packSer.GetAll().ToArray(); // 获取所有包装类型

            // 说明用户输入了关键字
            if (!string.IsNullOrEmpty(keyword))
            {
                GoodListPostModel model2 = SearchGoodsByDesc(keyword, index, packs);
                return Json(model2);
            }

            GoodListPostModel model = GetGoodsByPostWay(categoryId, index, orderBy, priceRange, packId, keyword, packs);
            return Json(model);

        }

        // 筛选出符合条件的商品方法
        public GoodListPostModel GetGoodsByPostWay(long categoryId, int index, string orderBy, string priceRange, long packId, string keyword, PackDTO[] packs)
        {
            var goods = goodSer.GetPageDataGoodsByCategId(categoryId, index, orderBy, priceRange, packId, keyword).ToArray();
            List<GoodImgSrcDTO> goodImgs = GetGoodsImg(goods); // 获取指定商品的图片
            List<int> goodComments = GetGoodComments(goods); // 获取指定商品的评论数
            ViewBag.goodCount = goodSer.GetGoodsByCategId(categoryId).Count(); // 获取所有商品总数

            GoodListPostModel model = new GoodListPostModel();

            model.Packs = packs;
            model.Goods = goods;
            model.GoodImgs = goodImgs;
            model.GoodComments = goodComments;
            return model;
        }

        /// <summary>
        /// 通过文本框搜索商品
        /// </summary>
        /// <param name="keyword">关键字</param>
        /// <param name="index">获取第几页数据</param>
        /// <param name="packs">包装类型</param>
        /// <returns></returns>
        public GoodListPostModel SearchGoodsByDesc(string keyword, int index, PackDTO[] packs)
        {
            var query = new QueryBuilder<GoodDTO>()
               .Query(b =>
                b.Bool(m =>
               //并且关系
               m.Must(t =>
                //分词的最小单位或关系查询
                t.QueryString(t1 => t1.DefaultField("Descible").Query(keyword))/*.QueryString(t1 => t1.DefaultField("Name").Query(keyword))*/
                )
                )
               ).From((index - 1) * 5).Size(2)
               ;

            var query2 = new QueryBuilder<GoodDTO>()
              .Query(b =>
               b.Bool(m =>
              //并且关系
              m.Must(t =>
               //分词的最小单位或关系查询
               t.QueryString(t1 => t1.DefaultField("Name").Query(keyword))/*.QueryString(t1 => t1.DefaultField("Name").Query(keyword))*/
               )
               )
              ).From((index - 1) * 5 + 2).Size(3)
              ;
            GoodDTO[] goodDtos1 = LuShanTeaElasticSearch.Search(query); // 接受搜索到的商品
            GoodDTO[] goodDtos2 = LuShanTeaElasticSearch.Search(query2); // 接受搜索到的商品
            GoodDTO[] goodDtos = goodDtos1.Concat(goodDtos2).ToArray();
            ViewBag.goodCount = goodDtos.Count();
            List<GoodImgSrcDTO> goodImgs2 = GetGoodsImg(goodDtos); // 获取指定商品的图片
            List<int> goodComments2 = GetGoodComments(goodDtos); // 获取指定商品的评论数
            GoodListPostModel model2 = new GoodListPostModel();

            model2.Packs = packs;
            model2.Goods = goodDtos;
            model2.GoodImgs = goodImgs2;
            model2.GoodComments = goodComments2;
            return model2;


        }


        /// <summary>
        /// 获取指定商品下的图片
        /// </summary>
        /// <param name="goods">商品</param>
        /// <returns>返回一个图片集合</returns>
        public List<GoodImgSrcDTO> GetGoodsImg(GoodDTO[] goods)
        {
            List<GoodImgSrcDTO> listGoodImg = new List<GoodImgSrcDTO>();
            // 遍历这8个商品，获取指定商品id的图片
            foreach (var good in goods)
            {
                long goodId = good.Id;
                var goodImg = goodImgSer.GetImgsByGoodId(goodId).ToArray();
                if (goodImg.Count() > 0)
                    listGoodImg.Add(goodImg[0]); // 只获取第一张图片
                else
                {
                    listGoodImg.Add(goodImgSer.GetImgSrcByCategoryId(good.CateGoriesId));
                }

            }
            return listGoodImg;
        }


        public List<GoodImgSrcDTO> GetGoodsImgs(GoodDTO[] goods)
        {
            List<GoodImgSrcDTO> listGoodImg = new List<GoodImgSrcDTO>();
            // 遍历这8个商品，获取指定商品id的图片
            foreach (var good in goods)
            {
                long goodId = good.Id;
                var goodImg = goodImgSer.GetImgsByGoodId(goodId).ToArray();
                if (goodImg.Count() > 0)
                {
                    // 遍历循环，获取该商品的所有图片
                    foreach (var img in goodImg)
                    {
                        listGoodImg.Add(img);
                    }
                    
                }
                else
                {
                    // 如果该商品还没有上传商品，则给他一个默认的图片
                    listGoodImg.Add(goodImgSer.GetImgSrcByCategoryId(good.CateGoriesId));
                }

            }
            return listGoodImg;
        }

        /// <summary>
        /// 获取指定商品的评论数
        /// </summary>
        /// <param name="goods">商品</param>
        /// <returns>返回该商品的评论数</returns>
        public List<int> GetGoodComments(GoodDTO[] goods)
        {
            List<int> list = new List<int>();
            // 遍历每件热销的商品，获取他的评论数
            foreach (var good in goods)
            {
                long id = good.Id;
                int count = commentSer.GetAll().Where(e => e.GoodId == id).Count();
                list.Add(count);
            }
            return list;
        }
        /// <summary>
        /// 获取商品评论
        /// </summary>
        /// <param name="goodId"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetGoodComment(long goodId, int index = 1)
        {
            if (goodSer.GetByGoodId(goodId) == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "商品不存在" });
            }
            GetGoodCommentModel model = new GetGoodCommentModel();
            long dataCount = commentSer.GetDataCommentCountByGoodId(goodId);
            //获取总页数
            model.PageCount = (int)Math.Ceiling((double)dataCount / 10);
            if (model.PageCount < 1)
            {
                return Json(new AjaxResult { Status = "no" });
            }
            //获取总数据条数
            model.DataCount = dataCount;

            if (index < 1)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "已是第一页" });
            }
            if (index > model.PageCount)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "已是最后一页" });
            }
            //获取第index页的数据
            model.Comments = commentSer.GetPageDataComment(goodId, index);

            model.OrderRecords = OrderRecordSer.GetORPackIdByCommentIds(model.Comments.Select(e => e.Id));
            model.PageIndex = index;
            return Json(new AjaxResult { Status = "ok", Data = model });
        }

        [HttpPost]
        [IsLogin]
        public ActionResult GetCartRecord()
        {
            var userId = (long)Session["USERID"];

            var cartId = CartService.GetCartIdByUserId(userId);

            CartIndexModel model = new CartIndexModel();

            model.CartRecordDTOs = CartRecordService.GetNoBuyCartByCartId(cartId);
            model.GoodImgSrcDTOs = GoodImgSrcService.GetFirstImgByGoodId(model.CartRecordDTOs.Select(e => e.GoodId));

            return Json(new AjaxResult { Status = "ok", Data = model });

        }
    }
}